{% extends 'base.combined.class' %}

{% block content %}
var {{ class_name }} = function() {

    var _findMax = function(nums) {
        var i = 0, l = nums.length, idx = 0;
        for (; i < l; i++) {
            idx = nums[i] > nums[idx] ? i : idx;
        }
        return idx;
    };

    var _normVals = function(nums) {
        var i, l = nums.length,
            result = [],
            sum = 0.;
        for (i = 0; i < l; i++) {
            sum += nums[i];
        }
        if(sum === 0) {
            for (i = 0; i < l; i++) {
                result[i] = 1.0 / l;
            }
        } else {
            for (i = 0; i < l; i++) {
                result[i] = nums[i] / sum;
            }
        }
        return result;
    };

    this._compute = function(features, post) {
        var classes = new Array({{ n_classes }}).fill(0);
        {{ tree | indent(4, True) }}
        return post(classes);
    };

    this.predict = function(features) {
        return this._compute(features, _findMax);
    };

    this.predictProba = function(features) {
        return this._compute(features, _normVals);
    };

};

var main = function () {
    if (typeof process !== 'undefined' && typeof process.argv !== 'undefined') {
        if (process.argv.length - 2 !== {{ n_features }}) {
            var IllegalArgumentException = function(message) {
                this.message = message;
                this.name = "IllegalArgumentException";
            }
            throw new IllegalArgumentException("You have to pass {{ n_features }} features.");
        }
    }

    // Features:
    var features = process.argv.slice(2);
    for (var i = 0; i < features.length; i++) {
        features[i] = parseFloat(features[i]);
    }

    // Estimator:
    var clf = new {{ class_name }}();

    {% if is_test or to_json %}
    // Get JSON:
    console.log(JSON.stringify({
        "predict": clf.predict(features),
        "predict_proba": clf.predictProba(features)
    }));
    {% else %}
    // Get class prediction:
    var prediction = clf.predict(features);
    console.log("Predicted class: #" + prediction);

    // Get class probabilities:
    var probabilities = clf.predictProba(features);
    for (var i = 0; i < probabilities.length; i++) {
        console.log("Probability of class #" + i + " : " + probabilities[i]);
    }
    {% endif %}
}

if (require.main === module) {
    main();
}
{% endblock %}